package com.koushikdutta.async.http;

import com.koushikdutta.async.http.libcore.RawHeaders;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class Multimap extends Hashtable<String, List<String>> implements Iterable<NameValuePair> {
    public String getString(String name) {
        List<String> ret = (List) get(name);
        if (ret == null || ret.size() == 0) {
            return null;
        }
        return (String) ret.get(0);
    }

    public void add(String name, String value) {
        List<String> ret = (List) get(name);
        if (ret == null) {
            ret = new ArrayList();
            put(name, ret);
        }
        ret.add(value);
    }

    public static Multimap parseHeader(String header) {
        if (header == null) {
            return null;
        }
        Multimap map = new Multimap();
        for (String part : header.split(";")) {
            String[] pair = part.split("=", 2);
            String key = pair[0].trim();
            String v = null;
            if (pair.length > 1) {
                v = pair[1];
            }
            if (v != null && v.endsWith("\"") && v.startsWith("\"")) {
                v = v.substring(1, v.length() - 1);
            }
            map.add(key, v);
        }
        return map;
    }

    public static Multimap parseHeader(RawHeaders headers, String header) {
        return parseHeader(headers.get(header));
    }

    public static Multimap parseUrlEncoded(String query) {
        Multimap map = new Multimap();
        for (String p : query.split("&")) {
            String[] pair = p.split("=", 2);
            if (pair.length != 0) {
                String name = URLDecoder.decode(pair[0]);
                String value = null;
                if (pair.length == 2) {
                    value = URLDecoder.decode(pair[1]);
                }
                map.add(name, value);
            }
        }
        return map;
    }

    public Iterator<NameValuePair> iterator() {
        ArrayList<NameValuePair> ret = new ArrayList();
        for (String name : keySet()) {
            for (String value : (List) get(name)) {
                ret.add(new BasicNameValuePair(name, value));
            }
        }
        return ret.iterator();
    }
}
